package com.qf.product.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.product.dto.PageDto;
import com.qf.product.entity.Product;
import com.qf.product.mapper.ProductMapper;
import com.qf.product.service.ProductService;
import com.qf.vo.PageResult;
import com.qf.vo.R;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author wxh
 * @since 2023-10-26
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    /**
     * 产品添加
     * @param product
     * @return
     */
    @Override
    public R add(Product product) {
        if (product == null) {
            return R.fail();
        }
        product.setDeleted(0);
        product.setPassword(SecureUtil.md5("123456"));
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());
        product.setTenantId(IdWorker.getIdStr());
        String key = "product"+"_"+product.getAreaCode()+"_"+IdWorker.getIdStr();
        product.setProductKey(key);
        product.setUsername(key);
        this.baseMapper.insert(product);

        return R.ok();
    }

    /**
     * 分页查询
     * @param pageDto
     * @return
     */
    @Override
    public PageResult<Product> page(PageDto<Product> pageDto) {
        //设置分页
        IPage<Product> page = new Page<>(pageDto.getNow(), pageDto.getSize());
        //产品查询没有条件

        //查询分页信息
        IPage<Product> pageInfo = this.baseMapper.selectPage(page, null);


        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setList(pageInfo.getRecords());

        return pageResult;

    }

    /**
     * 产品删除
     * @param product
     * @return
     */
    @Override
    public R deleteById(Product product) {
        if (product == null) {
            return R.fail();
        }
        int i = this.baseMapper.deleteById(product.getId());
        if (i != 1){
            return R.fail();
        }
        return R.ok();

    }
}
